package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"moxue_rpc/mysql"
	"moxue_rpc/pkg"
	"strconv"

	"moxue_rpc/internal/svc"
	"moxue_rpc/moxue"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *moxue.OrderAddRequest) (*moxue.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	var g mysql.Goods
	err := g.GoodsFind(int(in.GoodsId))
	if err != nil {
		logx.Info("商品查询失败")
		return nil, fmt.Errorf("商品查询失败")
	}
	fmt.Println(g.ID)
	if g.ID == 0 {
		logx.Info("商品不存在")
		return nil, fmt.Errorf("商品不存在")
	}
	var u mysql.User
	err = u.UserFind(int(in.UserId))
	if err != nil {
		logx.Info("用户查询失败")
		return nil, fmt.Errorf("用户查询失败")
	}
	if u.ID == 0 {
		logx.Info("用户不存在")
		return nil, fmt.Errorf("用户不存在")
	}
	OrderNo := uuid.NewString()
	order := mysql.Order{
		OrderNo: OrderNo,
		UserId:  int(in.UserId),
		GoodsId: int(in.GoodsId),
		Price:   g.Price,
		State:   0,
	}
	PayURL := pkg.Alipay(OrderNo, strconv.Itoa(int(g.Price)))
	mysql.DB.Debug().Create(&order)

	return &moxue.OrderAddResponse{
		PayURL: PayURL,
	}, nil
}
